const $ = require('selenium-query');

const _getMyCourseBtn = $browser => () => {
    const myCourseBtn = $browser.find('.dropdown--mycourses');
    return myCourseBtn.find('.dropdown__main-link').data('purpose')
            .then((myCoursePageLink) => {
                if (!myCoursePageLink) {
                    return _getMyCourseBtn($browser)();
                }

                return myCourseBtn;
            });
};

const _getCourseList = $browser => () => {
    const courseContainer = $browser.find('.my-courses__container');

    return courseContainer.find('.card').attr('course')
        .then((courseItem) => {
            if (!courseItem) {
                return _getCourseList($browser)();
            }

            return courseContainer.find('.card');
        });
};

const getCourseInfo = browser => () => {
    const $browser = $(browser);
    const getMyCourseBtn = _getMyCourseBtn($browser);
    const getCourseList = _getCourseList($browser);

    return getMyCourseBtn()
        .then(myCourseBtn => $(myCourseBtn).click())
        .then(() => getCourseList())
        .then(courseList => courseList.map((item) => {
            const tmpObj = {};
            return $(item)
                    .find('.card--learning__image').attr('href')
                    .then(link => Object.assign(tmpObj, { link }))
                    .then(() => $(item).find('.details__name').text())
                    .then(title => Object.assign(tmpObj, {
                        title: title.trim(),
                    }))
                    .then(() => $(item).find('.details__instructor').text())
                    .then(instructor => Object.assign(tmpObj, {
                        instructor: instructor.trim(),
                    }));
        }).toArray());
        // .then(res => console.log(res));
};

module.exports = getCourseInfo;
